<template>
  <div id="globalSider">
    <a-layout-sider width="145" collapsible defaultCollapsed>
      <a-menu
        v-model:selectedKeys="current"
        mode="inline"
        :items="menuItems"
        @click="doMenuClick"
      />
    </a-layout-sider>
  </div>
</template>

<script lang="ts" setup>
import { computed, h, ref, watchEffect } from 'vue'
import { HomeOutlined, UsergroupAddOutlined, CloudOutlined } from '@ant-design/icons-vue'
// @ts-ignore
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStores.ts'
import { SPACE_TYPE_ENUM } from '@/constants/space.ts'
import { listMyTeamSpaceUsingPost } from '@/api/spaceUserController.ts'

const loginUserStore = useLoginUserStore()
// 使用 computed 属性获取登录用户的信息
const loginUser = computed(() => loginUserStore.loginUser)
// 使用 computed 属性获取登录用户的角色
const loginUserRole = computed(() => loginUserStore.loginUser.userRole)
const router = useRouter()

// 固定的侧边栏列表
const fixedMenuItems = [
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '公共云图库',
    title: '公共云图库',
  },
  {
    key: '/my_space',
    icon: () => h(CloudOutlined),
    label: '我的个人云',
    title: '我的个人云',
  },
  {
    key: '/add_space?type=' + SPACE_TYPE_ENUM.TEAM,
    icon: () => h(UsergroupAddOutlined),
    label: '创建团队云',
    title: '创建团队云',
  },
]

const teamSpaceList = ref<API.SpaceUserVO[]>([])
const menuItems = computed(() => {
  // 如果用户没有处于任何团队空间中，那么展示固定侧边栏即可
  if (teamSpaceList.value.length < 1) {
    return fixedMenuItems
  }
  // 有团队空间，则展示固定侧边栏 + 团队空间菜单
  const teamSpaceSubMenus = teamSpaceList.value.map((spaceUser) => {
    const space = spaceUser.space
    return {
      key: '/space/' + spaceUser.spaceId,
      label: space?.spaceName,
    }
  })
  const teamSpaceMenuGroup = {
    type: 'group',
    label: '我的团队',
    key: 'teamSpace',
    children: teamSpaceSubMenus,
  }
  return [...fixedMenuItems, teamSpaceMenuGroup]
})

// 加载团队空间列表
const fetchTeamSpaceList = async () => {
  const res = await listMyTeamSpaceUsingPost()
  if (res.data.code === 0 && res.data.data) {
    teamSpaceList.value = res.data.data
  } else {
    message.error('加载我的团队空间失败，' + res.data.message)
  }
}

/**
 * 监听变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  // 登录才加载
  if (loginUserStore.loginUser.id) {
    fetchTeamSpaceList()
  }
})

/**
 * 菜单路由跳转
 */
// @ts-ignore
const doMenuClick = ({ key }) => {
  if (key !== 'others') {
    router.push(key)
  }
}

const current = ref<string[]>([])
router.afterEach((to, from, next) => {
  current.value = [to.path]
})

/**
 * 跳转编辑个人资料页面
 */
const toEditMyselfPage = async () => {
  // todo
}
</script>

<style scoped>
#globalSider .ant-layout-sider {
  background: none;
}
</style>
